<template>
  <div class="i18n">
    <h1>i18n</h1>
    <h2>{{ $t('app.welcome') }}</h2>
    <button @click="switchLanguage('zhCN')">简体中文</button>
    <button @click="switchLanguage('zhHK')">繁体中文</button>
    <button @click="switchLanguage('en')">English</button>
    <div>{{availableLocales}}</div>
  </div>
</template>

<script setup>
import { onMounted } from 'vue';
const { locale, locales, t, setLocale } = useI18n();

const switchLanguage = (lang) => {
  localStorage.setItem('user-locale', lang);
  setLocale(lang)
};


const localeName = ref("");
localeName.value = locales.value.filter(i => i.code === locale.value)[0].name ?? "";
const availableLocales = computed(() => {
  localeName.value = locales.value.filter(i => i.code === locale.value)[0].name ?? "";
  return locales.value.filter(i => i.code !== locale.value)
})

onMounted(() => {
  // 从 localStorage 中读取用户之前选择的语言
  const savedLocale = localStorage.getItem('user-locale');
  if (savedLocale) {
    setLocale(savedLocale);
  } else {
    // 根据浏览器语言自动选择
    const browserLang = navigator.language || navigator.userLanguage;
    if (browserLang.startsWith('zh')) {
      if (browserLang.includes('HK') || browserLang.includes('TW')) {
        setLocale('zh-HK');
      } else {
        setLocale('zh-CN');
      }
    } else {
      setLocale('en');
    }
  }
});

</script>

<style scoped>
/* 样式内容 */
</style>